<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="合同编号" size="small">
            <el-input v-model="searchForm.contractCode"></el-input>
          </el-form-item>
        </el-col>
        <!--<el-col class="other">-->
          <!--<el-form-item label="申请部门" size="small">-->
            <!--<el-input v-model="searchForm.teamName"></el-input>-->
          <!--</el-form-item>-->
        <!--</el-col>-->
        <el-col class="other">
          <el-form-item label="申请人" size="small">
            <el-input v-model="searchForm.sealPerson"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="文件名称" size="small">
            <el-input v-model="searchForm.sealFile"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="用印理由" size="small">
            <el-input v-model="searchForm.sealReason"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>
      <el-button type="primary" size="small" icon="el-icon-upload2" @click="downloadFile">导入</el-button>
      <input type="file" @change="fileChanged" ref="file"/>
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="650px">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
          <el-row>
            <el-col class="dialog-line">
              <el-form-item prop="sealPerson" label="申请人" size="small">
                <el-autocomplete
                  style="width: 190px"
                  v-model="teamRow.sealPerson"
                  :fetch-suggestions="querySearchOperator"
                  @select="handleSelectName"
                  placeholder="请输入内容"
                >
                </el-autocomplete>
              </el-form-item>
              <el-form-item key="contractCode" label="合同编号" size="small">
                <el-autocomplete
                  v-model="teamRow.contractCode"
                  :fetch-suggestions="querySearchProject"
                  @select="handleSelectProject"
                  placeholder="请输入内容"
                >
                </el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col class="dialog-line">
              <el-form-item v-if="teamRow.teamName" label="申请部门" size="small">
                {{teamRow.teamName}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item v-if="teamRow.projectName" label="合同项目" size="small">
            {{teamRow.projectName}}
          </el-form-item>
          <el-row>
            <el-col class="dialog-line">
              <el-form-item prop="startTime" label="申请日期" size="small">
                <el-date-picker
                  v-model="teamRow.startTime"
                  type="date"
                  value-format="timestamp"
                  placeholder="选择日期"
                  style="width: 190px"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item prop="sealFile" label="用印文件名称" size="small">
                <el-input type="text" v-model="teamRow.sealFile"></el-input>
              </el-form-item>
              <el-form-item label="公章" size="small">
                <el-input type="number" v-model.number="teamRow.commonSeal"></el-input>
              </el-form-item>
              <el-form-item label="法人章" size="small">
                <el-input type="number" v-model.number="teamRow.corporateSeal"></el-input>
              </el-form-item>
              <el-form-item label="合同章" size="small">
                <el-input type="number" v-model.number="teamRow.contractSeal"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="dialog-line">
              <el-form-item prop="sealReason" label="用印理由" size="small">
                <el-input type="text" v-model="teamRow.sealReason"></el-input>
              </el-form-item>
              <el-form-item label="出图章" size="small">
                <el-input type="number" v-model.number="teamRow.plotSeal"></el-input>
              </el-form-item>
              <el-form-item label="注册章" size="small">
                <el-input type="number" v-model.number="teamRow.registerSeal"></el-input>
              </el-form-item>
              <el-form-item label="技术章" size="small">
                <el-input type="number" v-model.number="teamRow.technologySeal"></el-input>
              </el-form-item>
              <el-form-item label="鉴定章" size="small">
                <el-input type="number" v-model.number="teamRow.authenticateSeal"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注说明" size="small">
            <el-input type="textarea" v-model="teamRow.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
          <el-button size="small" @click="outerVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
    >
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="120">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.sealId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import {
    delUse,
    getList,
    insertUse,
    selectUse,
    updateUse,
    selectOperator,
    selectProjectName,
    batchInsertInfo
  } from '@/api/use'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { Message } from 'element-ui'
  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const time = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const completionAcceptanceReport = {
    props: ['colConfig'],
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        <div :style="{'color':scope.row.completionAcceptanceReport ? '#606266':'red'}">
          {{ scope.row[colConfig.prop] }}
        </div>
      </span>
  </el-table-column>
  `
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'startTime', label: '申请日期', width: '150', component: time, fixed: true },
          { prop: 'teamName', label: '申请部门', width: '150' },
          { prop: 'sealPerson', label: '申请人', width: '150' },
          { prop: 'contractCode', label: '合同编号', width: '150' },
          { prop: 'projectName', label: '合同项目', width: '250', component: completionAcceptanceReport },
          { prop: 'sealFile', label: '用印文件名称', width: '250', component: completionAcceptanceReport },
          { prop: 'sealReason', label: '用印理由', width: '150' },
          { prop: 'commonSeal', label: '公章/数量', width: '150' },
          { prop: 'corporateSeal', label: '法人章/数量', width: '150' },
          { prop: 'contractSeal', label: '合同章/数量', width: '150' },
          { prop: 'plotSeal', label: '出图章/数量', width: '150' },
          { prop: 'registerSeal', label: '注册章/数量', width: '150' },
          { prop: 'technologySeal', label: '技术章/数量', width: '150' },
          { prop: 'authenticateSeal', label: '鉴定章/数量', width: '150' },
          { prop: 'remark', label: '备注说明', width: '150' },
          { slot: 'opt' }
        ],
        noConfigs: [
          { prop: 'startTime', label: '申请日期', width: '150', component: time, fixed: true },
          { prop: 'teamName', label: '申请部门', width: '150' },
          { prop: 'sealPerson', label: '申请人', width: '150' },
          { prop: 'sealFile', label: '用印文件名称', width: '250', component: completionAcceptanceReport },
          { prop: 'sealReason', label: '用印理由', width: '150' },
          { prop: 'commonSeal', label: '公章/数量', width: '150' },
          { prop: 'corporateSeal', label: '法人章/数量', width: '150' },
          { prop: 'contractSeal', label: '合同章/数量', width: '150' },
          { prop: 'plotSeal', label: '出图章/数量', width: '150' },
          { prop: 'registerSeal', label: '注册章/数量', width: '150' },
          { prop: 'technologySeal', label: '技术章/数量', width: '150' },
          { prop: 'authenticateSeal', label: '鉴定章/数量', width: '150' },
          { prop: 'remark', label: '备注说明', width: '150' }
        ],
        searchForm: {},
        searchFormList: {},
        professions: [],
        typeNames: [],
        listLoading: true,
        dialogTitle: '新增印章使用登记表',
        dialogType: 0,
        teamRow: {},
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        pca: pca,
        rules: {
          startTime: [
            { required: true, message: '请选择申请日期', trigger: 'change' }
          ],
          sealFile: [
            { required: true, message: '请输入用印文件名称', trigger: 'change' }
          ],
          sealPerson: [
            { required: true, message: '请输入申请人', trigger: 'change' }
          ],
          sealReason: [
            { required: true, message: '请输入用印理由', trigger: 'change' }
          ]
        },
        visible: false
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    computed: {
      global() {
        return global
      },
      roleType() {
        return this.$store.state.user.roleType
      },
      teamId() {
        return this.$store.state.user.teamId
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '新增印章使用登记表'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
        this.$set(this.teamRow, 'teamId', this.teamId)
      },
      editTeam(sealId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改印章使用登记表'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 0
        const params = {
          sealId: sealId
        }
        selectUse(params).then(response => {
          this.teamRow = Object.assign({}, this.teamRow, response.responseBody)
        })
      },
      submitForm(formName) {
        // const isProject = this.teamRow.contractCode && !this.teamRow.projectId ? 0 : 1
        const params = {
          projectId: this.teamRow.projectId,
          projectName: this.teamRow.projectName,
          sealPerson: this.teamRow.sealPerson,
          teamId: this.teamRow.teamId,
          teamName: this.teamRow.teamName,
          startTime: this.teamRow.startTime,
          contractCode: this.teamRow.contractCode,
          sealFile: this.teamRow.sealFile,
          sealReason: this.teamRow.sealReason,
          commonSeal: this.teamRow.commonSeal,
          corporateSeal: this.teamRow.corporateSeal,
          contractSeal: this.teamRow.contractSeal,
          authenticateSeal: this.teamRow.authenticateSeal,
          plotSeal: this.teamRow.plotSeal,
          registerSeal: this.teamRow.registerSeal,
          technologySeal: this.teamRow.technologySeal,
          remark: this.teamRow.remark || ''
        }
        if (!this.dialogType) {
          params.sealId = this.teamRow.sealId
        }
        // if (isProject) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogType) {
              insertUse(params).then(response => {
                this.outerVisible = false
                this.fetchData()
              })
            } else {
              updateUse(params).then(response => {
                this.outerVisible = false
                this.fetchData()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
        // } else {
        //   this.$message({
        //     message: '该合同编号不存在',
        //     type: 'warning'
        //   })
        // }
      },
      deleteRow(scope) {
        console.log(this.$refs[`popover-${scope.$index}`])
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          sealId: scope.row.sealId,
          isDel: 1
        }
        delUse(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      querySearchOperator(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            name: queryString
          }
          selectOperator(params).then(response => {
            for (const i of response.responseBody) {
              if (i.tertiarySector) {
                i.teamName = i.tertiarySector
              } else {
                let obj = {}
                obj = global.secondarySectorList.find((items) => {
                  return items.value === i.secondarySector // 筛选出匹配数据
                })
                i.teamName = obj.label
              }
              i.value = i.teamName + ' ' + i.name
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectName(item) {
        this.$set(this.teamRow, 'sealPerson', item.name)
        this.$set(this.teamRow, 'teamName', item.teamName)
      },
      querySearchProject(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.projectId
        if (queryString) {
          const params = {
            contractCode: queryString
          }
          selectProjectName(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.contractCode
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectProject(item) {
        this.$set(this.teamRow, 'projectId', item.projectId)
        this.$set(this.teamRow, 'contractCode', item.contractCode)
        this.$set(this.teamRow, 'projectName', item.projectName)
      },
      downloadFile() {
        this.$refs.file.click()
      },
      fileChanged() {
        const excel = this.$refs.file.value
        const params = new FormData()
        console.log(this.$refs.file.value)
        var reg = /^.*\.(?:xls|xlsx)$/i
        if (!reg.test(excel)) {
          Message({
            message: '请上传excel格式的文件!',
            type: 'error',
            duration: 5 * 1000
          })
          return
        } else {
          params.append('file', this.$refs.file.files[0])
          batchInsertInfo(params).then(response => {
            this.fetchData()
          })
          if (this.$refs.file) {
            this.$refs.file.value = ''
          }
        }
      }
    },
    mounted() {
      console.log(this.pca)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
    input[type="file"] {
      display: none;
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
